/**
 * User: 86156
 * Date: 2023-04-15
 * Time: 14:37
 */

// 动态数组

public class DynamicArray {
    private int size = 0; //逻辑大小
    private int capacity = 8; // 实际容量
    private int[] arr ={}; // 懒初始化,用到的时候在初始化,节省空间


    public void add(int index,int element) {
        // 动态检查
        checkCapacity();

        if(size<0){
            System.out.println("索引不符合规范");
            return;
        }

        if (index >= 0 && index < size) {
            System.arraycopy(arr, index, arr, index + 1, size - index);
        }
        arr[index] = element;
        size++;
    }

    private void checkCapacity() {
        if(size == 0){
            arr = new int[capacity];
        }else if (size == capacity) {
            // java中扩容为原来的1.5倍
            capacity += capacity/2;
            int[] newArr = new int[capacity];
            System.arraycopy(arr, 0, newArr, 0, size);
            arr = newArr;
        }
    }
}
